import {Provider} from 'react-redux';
import {store, persistor} from './src/store';
import {View, Text, Button} from 'react-native';
import {useSelector, useDispatch} from 'react-redux';
import {
  selectCount,
  increment,
  incrementByAmount,
} from './src/store/counter/counterSlice';
import {PersistGate} from 'redux-persist/integration/react';
import {useEffect, useState} from 'react';
import {addBookAPI, getBooksAPI, IBook} from './src/services/bookService';
export default function App() {
  const [books, setBooks] = useState<IBook[]>([]);

  // 调用获取图书列表的接口
  useEffect(() => {
    getBooksAPI().then(res => {
      setBooks(res);
    });
  }, []);

  const onAdd = () => {
    addBookAPI({
      bookname: 'abc',
      author: 'bbc',
      publisher: Date.now().toString(),
    }).then(() => {
      getBooksAPI().then(res => {
        setBooks(res);
      });
    });
  };

  return (
    // 全局的状态管理 store
    <Provider store={store}>
      {/* 添加了持久化的状态管理的刷题 */}
      <PersistGate persistor={persistor}>
        {/* 遍历books数组 生成书籍列表 */}
        {books.map(v => (
          <Text key={v.id}>
            {v.author}-{v.bookname}-{v.publisher}
          </Text>
        ))}
        <Button title="新增书籍" onPress={onAdd} />
        <Son />
      </PersistGate>
    </Provider>
  );
}

function Son() {
  const count = useSelector(selectCount);
  // 获取到 派发  动作的对象
  const dispatch = useDispatch();
  return (
    <View>
      <Text>Son {count}</Text>
      {/* 增加 */}
      <Button title="增加222" onPress={() => dispatch(increment())} />
      {/* 增加 30 */}
      <Button
        title="增加3330"
        onPress={() => dispatch(incrementByAmount(30))}
      />
    </View>
  );
}
